import { Button, Form, Input, message } from 'antd';
import style from "./style.module.scss";
import http from '@/api/axios';
import { useLocation, useNavigate } from 'react-router-dom';
import { enc, SHA256 } from 'crypto-js';
import { Vertify } from '@alex_xu/react-slider-vertify';
import { useState } from 'react';

export default function Login() {
  const navigate = useNavigate();
  const location = useLocation();
  const [captchaVerified, setCaptchaVerified] = useState(false);
  const [captchaVisible, setCaptchaVisible] = useState(false);


  const handleLogin = async (values: { username: string, password: string }) => {

    // 验证验证码
    if (!captchaVerified) {
      message.error('请完成安全验证');
      return;
    }
    try {
      // 加盐哈希密码
      const salt = Date.now().toString(36);
      const hashedPassword = enc.Base64.stringify(SHA256(values.password + salt));

      const res = await http.post('/api/auth/login', {
        username: values.username,
        password: hashedPassword,
        salt
      }, { needToken: false });
      if (res.data.code !== 200) {
        message.error('用户名或密码错误');
        return;
      }

      // 存储token
      localStorage.setItem('token', res.data.token);
      localStorage.setItem('user', JSON.stringify(res.data.data.user));
      message.success('登录成功');

      const from = location.state?.from?.pathname || '/';
      navigate(from, { replace: true });

    } catch (error: any) {
      message.error(error.message || '登录失败，请稍后重试');
    }
  };



  return (
    <div className={style.login}>
      <div className={style.main}>
        <h3>系统登录</h3>
        <Form
          name="login"
          labelCol={{ span: 6 }}
          initialValues={{ remember: true }}
          onFinish={handleLogin}
          autoComplete="off"
          className={style.form}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
            className={style.input}
          >
            <Input placeholder='admin/user' />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
            className={style.input}
          >
            <Input.Password placeholder='admin/user' />
          </Form.Item>

          <Form.Item
            className={style.captcha}
            style={{ display: captchaVerified ? 'none' : 'inlineblock' }}
          >
            <div
              className={style.captchaTrigger}
              onClick={() => setCaptchaVisible(true)}
            >
              点击进行安全验证
            </div>
          </Form.Item>

          <Form.Item
            className={style.btn}
            style={{ display: captchaVerified ? 'block' : 'none' }}
          >
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>

        {/* 验证码弹窗 */}
        {captchaVisible && (
          <div className={style.captchaModal}>
            <div className={style.captchaContent}>
              <div className={style.captchaHeader}>
                <h4>安全验证</h4>
                <button
                  className={style.closeButton}
                  onClick={() => setCaptchaVisible(false)}
                >
                  &times;
                </button>
              </div>

              <Vertify
                width={320}
                height={160}
                onSuccess={() => {
                  setCaptchaVerified(true);
                  message.success('验证成功');
                  setTimeout(() => setCaptchaVisible(false), 1000);
                }}
                onFail={() => message.error('验证失败，请重试')}
                onRefresh={() => message.info('已刷新验证码')}
                text="向右滑动完成验证"
              />
            </div>
          </div>
        )}
      </div >
    </div>
  )
}